<?php

/**
 * gallery actions.
 *
 * @package    sf_sandbox
 * @subpackage gallery
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class cropActions extends sfActions
{
    /**
     * 
     * if cropping for blog
     */
    public function executeBlog()
    {
        $this->objType = MyConstants::TYPE_BLOG_PROFILE;
        $this->objId = BlogUserInfo::getInstance()->getBlogInfo()->getId();
        $this->setFlash('blog', 'blog');
        $this->arFiles = Files::getByObj($this->objType, $this->objId);
        $this->setFlash('returnCrop', $this->getFlash('returnCrop'));
    }
    public function handleErrorPhotos()
    {
        if($this->hasFlash('blog'))
            $this->redirect('crop/blog');
        return sfView::SUCCESS;
    }
    /**
     * 
     * show all photos for this object and upload new befor cropping
     * @throws Exception
     */
    public function executePhotos()
    {
        
        $objType = $this->getRequestParameter('type');
        $objId = $this->getRequestParameter('id');
        $this->objType = $objType;
        $this->objId = $objId;
        
        $this->arFiles = Files::getByObj($objType, $objId);
        $this->setFlash('returnCrop', $this->getFlash('returnCrop'));
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            //save uploaded image in temporary directory, and save data about this file in session
            $fileName = $this->getRequest()->getFileName('photo');
            $filePath = $this->getRequest()->getFilePath('photo');
            $arFile = $this->getRequest()->getFile('photo');
            $bExt = substr($fileName, strrpos($fileName, '.') + 1);
            $ext = strtolower($bExt);
            $path = 'temporary';
            if (!file_exists($path))
            {
                @mkdir($path, 0777);
            }
            $this->name = md5($fileName . $objId . $objType) . '.' .  $ext;
            $newFile = $path . '/' . $this->name;
            $this->path = $path;
            if( !@copy($filePath, $newFile) )
                throw new Exception('File not uploaded.');
            $type = $arFile['type'];
            
            //save data about this file in session
            /* @var $info TempFileInfo */
            $info = new TempFileInfo();
            $info->setFileExtension($ext);
            $info->setFileName($this->name);
            $info->setFileType($type);
            $info->setTempDir($path);
            $info->setObjId($objId);
            $info->setObjType($objType);
            $info->setFilei18nName($this->getRequestParameter('gallery[photoname]'));
            $info->setFileText($this->getRequestParameter('gallery[phototext]'));
            $info->setState(1);
            $this->dirs = Files::getPhotoDirs();
            if( $objType == MyConstants::TYPE_BLOG_PROFILE )
            {
                $this->dirs = BlogUserInfo::getPhotoDirs();
            }
            $info->setArDirectories($this->dirs);
            $info->setReturnUrl($this->getFlash('returnCrop'));
            $this->getUser()->setAttribute('cropInfo', $info);
            
            $h = sfConfig::get('app_image_screen_size_h');
            $w = sfConfig::get('app_image_screen_size_w');
            list($width, $height) = getimagesize($newFile); 
            //check if image not to big for screen
            ACrop::reduceToWindowSize($h, $w, $height, $width, $newFile, $type);
            $this->redirect('crop/crop');
        }
    }
    /**
     * 
     * croping by state
     * @throws Exception
     */
    public function executeCrop()
    {
        /* @var $info TempFileInfo */
        $info = $this->getUser()->getAttribute('cropInfo');
        $this->forward404Unless($info);
        if($getState = $this->getRequestParameter('state'))
        {
            if($getState<0)
            {
                $getState = 1;
            }
            if($getState>count($info->getArDirectories()))
            {
                $this->redirect('crop/summary');
            }
            $info->setState($getState);
        }
        $state = $info->getState();
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            $name = $info->getFileName();
            $path = $info->getTempDir();
            $dir = $info->getDirByCurrentState();
            $file = $path .'/'.$name;
            $newFile = 'images/gallery/' . $dir .'/'.$name;
            if(!@copy($file, $newFile))
            {
                throw new Exception('Cannot make file copy');
            }
            $x1 = $this->getRequestParameter('x1');
            $y1 = $this->getRequestParameter('y1');
            $width = $this->getRequestParameter('width');
            $height = $this->getRequestParameter('height');
            $img = new sfImage($newFile, $info->getFileType());
            $cr = new ACrop($x1, $y1, $width, $height);
            $imgn = $cr->transform($img);
            $imgn->save();
            $img3 = new sfImage($newFile, $info->getFileType());
            //Resize works when width or height is null
            if( !$info->getWidthByState() || !$info->getHeightByState() )
            {
                $res = $img3->resize($info->getWidthByState(), $info->getHeightByState());
            }
            else
            {
                $thumb = sfConfig::get('app_symcms_files_thumb_type');
                $res = $img3->thumbnail($info->getWidthByState()
                                    , $info->getHeightByState()
                                    , $thumb);
            }
            if( $res )
            {
                $img3->save();
            }
            
            
            
            if( $state > $info->getCountDirs())
            {
                $this->redirect('crop/summary');
            }else 
            {
                $info->setState($state+1);
                $this->getUser()->setAttribute('cropInfo', $info);
                $this->redirect('crop/crop');
            }
        }else 
        {
            if( $state > $info->getCountDirs())
            {
                $this->redirect('crop/summary');
            }
            $this->name = $info->getFileName();
            $this->path = $info->getTempDir();
            $this->state = $info->getState();
            $this->dir = $info->getDirByCurrentState();
            $this->h = $info->getHeightByState();
            $this->w = $info->getWidthByState();
        }
        
    }

    public function executeCancelCrop()
    {
        $info = $this->getUser()->getAttribute('cropInfo');
        @unlink($info->getTempDir().'/'.$info->getFileName());
        foreach ($info->getArDirectories() as $key=>$dir )
        {
            @unlink('images/gallery/'.$key.'/'.$info->getFileName());
        }
        $this->getUser()->getAttributeHolder()->remove('cropInfo');
        $this->redirect($info->getReturnUrl());
    }
    
    public function executeSummary()
    {
        /* @var $info TempFileInfo */
        $this->info = $this->getUser()->getAttribute('cropInfo');
        $this->forward404Unless($this->info);
        $this->state = $this->info->getCountDirs();
        $this->echo = 'THE END.';
    }
    /**
     * 
     * saves selected Crops
     */
    public function executeSaveCrop()
    {/* @var $info TempFileInfo */
        $info = $this->getUser()->getAttribute('cropInfo');
        $this->forward404Unless($info);
        $directories = $info->getArDirectories();
        
        // foreach directories, where must be saved photos
        foreach ( $directories as $dir )
        {
            // if file wasn`t cropped, create automatic
            if(!file_exists('images/gallery/' . $dir['dir']. '/'.$info->getFileName()))
            {
                if(!@copy($info->getTempDir().'/'.$info->getFileName(), 'images/gallery/' . $dir['dir']. '/'.$info->getFileName()))
                {
                    throw new Exception('Cannot make file copy');
                }
            }
        }
        Files::saveCropedTo($info->getFileName()
                        , 'images/gallery/' . $dir['dir']. '/'.$info->getFileName()
                        , $info->getObjId()
                        , get_user_id()?get_user_id():111
                        , $info->getObjType()
                        , $this->getUser()->getCulture()
                        , MyConstants::STATUS_APPROVED
                        , $info->getFilei18nName()
                        , $info->getFileText()
                        , $info->getArDirectories());
        @unlink($info->getTempDir().'/'.$info->getFileName());
        
        $this->getUser()->getAttributeHolder()->remove('cropInfo');
        $this->redirect($info->getReturnUrl());
    }

}
